#!/usr/bin/env python
# -*- coding:utf-8 -*-
import datetime

from utils import log

from sqlalchemy.orm import mapper, sessionmaker
from sqlalchemy import Table, MetaData, Column, Integer, Boolean, Unicode, UnicodeText, DateTime
from sqlalchemy.sql.sqltypes import TIMESTAMP
from sqlalchemy.sql import func
from controls.data_pool_mysql import engine

metadata = MetaData()
Session = sessionmaker()
Session.configure(bind=engine)

'''user_feed collection has
    id:             自增id(int)
    userid:         用户id(int)
    targetid:       话题id(int)
    optype:         操作类型(int)
    hide:           是否隐藏(bool)
    ctime:          创建时间(timestamp)
'''

USER_FEED_TYPE_TOPIC_LIKE, USER_FEED_TYPE_NOTE_POST, \
    USER_FEED_TYPE_NOTE_LIKE = range(3)

USER_FEED_TYPE_MAP = {
    USER_FEED_TYPE_TOPIC_LIKE: 'topic_like',
    USER_FEED_TYPE_NOTE_POST: 'note_post',
    USER_FEED_TYPE_NOTE_LIKE: 'note_like',
}


class UserFeedItem(object):
    def to_dict(self):
        res = {}
        res['feedid'] = self.id
        res['userid'] = self.userid
        res['targetid'] = self.targetid
        res['optype'] = self.optype
        res['hide'] = self.hide
        res['ctime'] = self.ctime.strftime("%Y-%m-%d %H:%M:%S")\
            if self.ctime else ""
        return res

    def __repr__(self):
        return "%d" % (self.userid)


user_feed_table = Table(
    'user_feed', metadata,
    Column('id', Integer, primary_key=True),
    Column('userid', Integer, index=True, nullable=False),
    Column('targetid', Integer, nullable=False),
    Column('optype', Integer, nullable=False),
    Column('hide', Boolean, nullable=False, default=False),
    Column('ctime', TIMESTAMP, server_default=func.now())
)

mapper(UserFeedItem, user_feed_table)  # 把表映射到类


def create_user_feed_table_if_not_exist():
    metadata.create_all(engine)  # 在数据库中生成表
    # mapper( UserBaseItem, user_base_table ) #把表映射到类


def add_user_feed_item(p_item):
    item = UserFeedItem()
    item.userid = p_item['userid']
    item.optype = p_item['optype']
    item.targetid = p_item['targetid']
    try:
        session = Session()
        session.add(item)  # 往session中添加内容
        session.flush()  # 保存数据
        session.commit()  # 数据库事务的提交,sisson自动过期而不需要关闭
        return True
    except Exception as e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()


def add_user_feed_item_with_time(p_item):
    item = UserFeedItem()
    item.userid = p_item['userid']
    item.optype = p_item['optype']
    item.targetid = p_item['targetid']
    item.ctime = datetime.datetime.strptime(p_item['ctime'], '%Y-%m-%d %H:%M:%S')
    try:
        session = Session()
        session.add(item)  # 往session中添加内容
        session.flush()  # 保存数据
        session.commit()  # 数据库事务的提交,sisson自动过期而不需要关闭
        return True
    except Exception as e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()


def del_user_feed(p_item):
    userid = p_item.get('userid', None)
    targetid = p_item.get('targetid', None)
    optype = p_item.get('optype', None)
    try:
        session = Session()
        feed_query = session.query(UserFeedItem)
        if userid:
            feed_query = feed_query.filter_by(userid=userid)
        if targetid:
            feed_query = feed_query.filter_by(targetid=targetid)
        if optype:
            feed_query = feed_query.filter_by(optype=optype)
        feed_query.delete()
        session.flush()
        session.commit()
        return True
    except Exception as e:
        log.exp(e)
        session.rollback()
        return None
    finally:
        session.close()



def get_user_feed_list_by_userid(p_userid, p_hide, begin, limit):
    try:
        if p_hide == 0 or p_hide == '0':
            p_hide = False
        else:
            p_hide = True

        session = Session()
        items = session.query(UserFeedItem)\
            .filter(UserFeedItem.userid == p_userid)\
            .filter(UserFeedItem.hide == p_hide)\
            .order_by(UserFeedItem.ctime.desc())\
            .offset(begin).limit(limit).all()
        return [item.to_dict() for item in items]
    except Exception as e:
        log.exp(e)
        return None
    finally:
        session.close()


def update_user_feed_hide(p_feedid_list, p_userid, p_hide):
    try:
        if p_hide == 0 or p_hide == '0':
            p_hide = False
        else:
            p_hide = True

        session = Session()
        session.query(UserFeedItem).filter(UserFeedItem.id.in_(p_feedid_list))\
            .filter_by(userid=p_userid)\
            .update({'hide': p_hide}, synchronize_session='fetch')
        session.flush()
        session.commit()
        return True
    except Exception as e:
        log.exp(e)
        session.rollback()
        return None
    finally:
        session.close()


if __name__ == '__main__':
    create_user_feed_table_if_not_exist()
